#include "capture.h"
#include <getopt.h>

#define CAMERA_NAME     "/dev/video0"
#define CAMERA_WIDTH    3840
#define CAMERA_HEIGHT   2160
#define SAVE_PATH       "./00.jpg"

static void usage(FILE *fp, int argc, char **argv) {
    fprintf(fp,
            "Usage: %s [options]\n\n"
            "Options:\n"
            "-d | --device name   Video device name  [/dev/video]\n"
            "-w | --width  num    Picture width num  [3840]\n"
            "-h | --height num    Picture height num [2160]\n"
            "-s | --save   path   Picture save path  [./00.jpg]\n"
            "\n",
            argv[0]);
}

static const char short_options[] = "d:w:h:s:";

static const struct option
        long_options[] = {
        {"device", required_argument, NULL, 'd'},
        {"width",  required_argument, NULL, 'w'},
        {"height", required_argument, NULL, 'h'},
        {"save",   required_argument, NULL, 's'},
        {0, 0, 0,                           0}
};

int main(int argc, char *argv[]) {
    char save_path[64];
    struct camera_type dummy;
    struct timeval start, end;

    TIME_GET(start);

    dummy.name = CAMERA_NAME;
    dummy.state = CAMERA_STATE_CLOSE;
    dummy.width = CAMERA_WIDTH;
    dummy.height = CAMERA_HEIGHT;
    dummy.buffers = NULL;
    dummy.n_buffers = 0;
    strcpy(save_path, SAVE_PATH);

    for (;;) {
        int index;
        int c;

        c = getopt_long(argc, argv,
                        short_options, long_options,
                        &index);
        if (-1 == c) {
            break;
        }

        switch (c) {
            case 0: /* getopt_long() flag */
                break;
            case 'd':
                dummy.name = optarg;
                break;
            case 'w':
                dummy.width = atoi(optarg);
                break;
            case 'h':
                dummy.height = atoi(optarg);
                break;
            case 's':
                strcpy(save_path, optarg);
                break;

            default:
                usage(stderr, argc, argv);
                exit(EXIT_FAILURE);
        }
    }
    LOG("device name    : %s\n", dummy.name);
    LOG("picture width  : %d\n", dummy.width);
    LOG("picture height : %d\n", dummy.height);
    LOG("picture save   : %s\n\n", save_path);

    camera_init(&dummy);
    camera_capture(&dummy, save_path);
    camera_close(&dummy);

    TIME_GET(end);
    LOG("use time : %ld us\n\n", TIME_USE(start, end));

    return 0;
}